package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Client;
import org.ahuanlien.crm.domain.LossRecord;
import org.ahuanlien.crm.mapper.ClientMapper;
import org.ahuanlien.crm.mapper.LossRecordMapper;
import org.ahuanlien.crm.query.LossRecordQueryObject;
import org.ahuanlien.crm.query.QueryObject;
import org.ahuanlien.crm.service.ILossRecordService;
import org.ahuanlien.crm.util.PageResult;
import org.ahuanlien.crm.vo.LossRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class LossRecordServiceImpl implements ILossRecordService {

	@Autowired
	private LossRecordMapper lossRecordMapper;

	@Autowired
	private ClientMapper clientMapper;

	public PageResult Query(LossRecordQueryObject qo) {
		Integer state = qo.getState();
		if (state == -1) {
			int count = lossRecordMapper.falseQueryForCount(qo);
			if (count == 0) {
				return new PageResult(count, Collections.EMPTY_LIST);
			}
			List<LossRecord> result = lossRecordMapper.falseQueryForList(qo);
			return new PageResult(count, result);

		} else if (state == -2) {
			int count = lossRecordMapper.lossQueryForCount(qo);
			if (count == 0) {
				return new PageResult(count, Collections.EMPTY_LIST);
			}
			List<LossRecord> result = lossRecordMapper.lossQueryForList(qo);
			return new PageResult(count, result);
		}
		return null;
	}

	public void saveOrUpdate(LossRecord record) {
		if (record.getId() != null) {
			lossRecordMapper.updateByPrimaryKey(record);
		} else {
			lossRecordMapper.insert(record);
		}
	}

	public void insertLossRecord(LossRecordVO vo) {
		Client client = clientMapper.selectByPrimaryKey(vo.getId());
		LossRecord lossRecord = new LossRecord();
		lossRecord.setLossDate(new Date());
		lossRecord.setClientName(client.getClientName());
		lossRecord.setChargeEmp(client.getChargeEmp());
		lossRecord.setRemark(vo.getRemark());
		lossRecord.setState(vo.getState());
		clientMapper.ChangeState(vo.getId(),vo.getState());
		lossRecordMapper.insert(lossRecord);
	}
}
